<template>
  <div class="personal-info avic-base-form">
    <a-form ref="formRef" v-bind="layout" :model="formData" :rules="validateMessages" layout="horizontal">
      <div class="basic-title">个人信息</div>
      <a-row>
        <a-col v-bind="formColLayout.cols">
          <a-form-item label="真实姓名" name="name">
            <a-input v-model:value="formData.name" placeholder="平台管理员" :maxlength="100" />
          </a-form-item>
          <a-form-item label="英文名" name="nameEn">
            <a-input v-model:value="formData.nameEn" placeholder="请输入英文名称" :maxlength="100" />
          </a-form-item>
          <a-form-item label="性别" name="sex">
            <a-radio-group v-model:value="formData.sex">
              <a-radio value="1">男</a-radio>
              <a-radio value="2">女</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-bind="formColLayout.cols">
          <a-form-item label="头像">
            <div style="display: flex; flex-direction: column">
              <a-upload
                ref="image"
                name="avatar"
                accept=".jpg,.png,.gif,.jpeg,.bmp"
                class="avatar-uploader"
                :show-upload-list="false"
                :action="upload.url"
                :headers="upload.headers"
                :before-upload="beforeUpload"
                @change="handleChange"
              >
                <img v-if="imageUrl" :src="imageUrl" class="user-avatar" alt="avatar" />
                <div v-else class="user-avatar defaultAvatar">
                  <avic-icon svg="UserOutlined" color="#ffffff" />
                </div>
              </a-upload>
              <div class="img-action">
                <a-button danger type="default" title="删除" :disabled="!imageUrl" style="margin-top: 15px" @click="handleDelete">
                  <template #icon>
                    <delete-outlined />
                  </template>
                  删除
                </a-button>
                <a-alert class="alert-text" message="请选择小于512KB的头像图片！" type="info" show-icon />
              </div>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <!-- 电子签名 -->
        <a-col v-bind="formColLayout.cols">
          <a-form-item label="电子签名">
            <div style="display: flex; flex-direction: column">
              <a-upload
                name="avatar"
                class="avatar-uploader"
                :show-upload-list="false"
                accept=".jpg,.png,.gif,.jpeg,.bmp"
                :action="uploadSignphoto.url"
                :headers="uploadSignphoto.headers"
                :before-upload="beforeUploadSignphoto"
                @change="handleSignphotoChange"
              >
                <img v-if="signphotoImageUrl" :src="signphotoImageUrl" alt="电子签名" class="user-avatar" />
                <div v-else class="user-avatar">
                  <loading-outlined v-if="signphotoLoading" />
                  <plus-outlined v-else />
                  <div class="ant-upload-text">上传电子签名</div>
                </div>
              </a-upload>
              <div class="img-action">
                <a-button
                  title="删除"
                  danger
                  type="default"
                  style="margin-top: 15px"
                  :disabled="!signphotoImageUrl"
                  @click="deleteSignphotoImage"
                >
                  <template #icon>
                    <delete-outlined />
                  </template>
                  删除
                </a-button>
                <a-alert class="alert-text" message="请选择小于512KB的签名图片！" type="info" show-icon />
              </div>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <div class="basic-title">联系方式</div>
      <a-row>
        <a-col v-bind="formColLayout.cols">
          <a-form-item label="手机号码" name="mobile">
            <a-input v-model:value="formData.mobile" type="text" placeholder="请输入手机号码" />
          </a-form-item>
          <a-form-item label="家庭电话" name="homeTel">
            <a-input v-model:value="formData.homeTel" type="text" placeholder="请输入家庭电话" />
          </a-form-item>
          <a-form-item label="邮箱地址" name="email">
            <a-input v-model:value="formData.email" type="text" placeholder="请填写邮箱地址" />
          </a-form-item>
          <a-form-item label="办公电话" name="officeTel">
            <a-input v-model:value="formData.officeTel" type="text" placeholder="请填写办公电话" />
          </a-form-item>
          <a-form-item label="传真" name="fax">
            <a-input v-model:value="formData.fax" type="text" placeholder="请填写传真" />
          </a-form-item>
          <a-form-item label="家庭住址" name="homeAddress">
            <a-textarea v-model:value="formData.homeAddress" :maxlength="100" :rows="4" placeholder="请填写家庭地址" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col v-bind="formColLayout1.cols">
          <a-form-item label="">
            <a-button type="primary" html-type="submit" style="margin-right: 8px; margin-left: 140px" @click="handleSave">
              <template #icon>
                <save-outlined />
              </template>
              保存
            </a-button>
            <a-button title="重置" :disabled="!isDataChange" @click="resetForm">
              <template #icon>
                <reload-outlined />
              </template>
              重置
            </a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import type { Rule } from 'ant-design-vue/es/form';
import type { FormInstance } from 'ant-design-vue';
import type { formDataType } from '../types';
import { getUserInfo, updateUserInfo, deleteLogo, deleteSignphoto } from '@/api/avic/system/UserSettingApi'; // 引入模块API
import { getToken, getCookie } from '@/utils/common-util';
import { TENANT_ID } from '@/store/user';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
const { proxy }: any = getCurrentInstance();
const layout = {
  labelCol: { flex: '0 0 120px' },
  wrapperCol: { flex: '1 1 0' }
};
const formColLayout = proxy.$colLayout2;
const formColLayout1 = proxy.$colLayout1;
const validateMessages: Record<string, Rule[]> = {
  name: [{ required: true, message: '请输入真实姓名！', trigger: 'blur' }],
  nameEn: [
    {
      pattern: /^[a-z A-Z]+$/,
      message: '请正确填写您的英文名!',
      trigger: ['blur', 'change']
    }
  ],
  sex: [{ message: '请选择性别！', trigger: 'blur' }],
  mobile: [proxy.$validateRegExp('phone')],
  homeTel: [proxy.$validateRegExp('homeTel')],
  email: [proxy.$validateRegExp('email')],
  officeTel: [proxy.$validateRegExp('tel')],
  homeAddress: [{ message: '请输入家庭住址！', trigger: 'blur' }],
  fax: [proxy.$validateRegExp('fax')]
};
const token = getToken();
const upload = {
  url: `${proxy.$settings.axiosRequestConfig.baseURL}/appsys/user/user/photo/upload`,
  headers: {
    'X-Access-Token': token
  }
};
// loading = ref<boolean>(false),
const imageUrl = ref<string>('');
const formRef = ref<FormInstance>();
// const checkFileSize = ref<boolean>(false);
const state = reactive({
  formData: {
    name: '',
    nameEn: '',
    sex: '',
    mobile: '',
    homeTel: '',
    email: '',
    officeTel: '',
    fax: '',
    homeAddress: ''
  }, // 表单数据
  initFormData: {}, // 初始化表单数据
  oldFormData: {}, // 旧表单数据
  isChangeForm: false,
  isDataChange: false
});
const { formData, initFormData, isChangeForm, isDataChange } = toRefs(state);

const userId = ref('');
const uploadSignphoto = reactive({
  url: `${proxy.$settings.axiosRequestConfig.baseURL}/appsys/user/user/sign/upload`,
  headers: {
    'X-Access-Token': token
  }
});
const signphotoLoading = ref(false);
const signphotoImageUrl = ref('');

onMounted(() => {
  getInfo();
  getTokenAvatar(`${proxy.$settings.axiosRequestConfig.baseURL}/appsys/user/user/photo/get`, 'imageUrl');
});
watch(
  () => formData,
  () => {
    if (isChangeForm.value) {
      isDataChange.value = true;
    }
  },
  { deep: true }
);
// 获取用户数据
function getInfo() {
  getUserInfo()
    .then((res: any) => {
      if (res.code === '200') {
        userId.value = res.data.id;
        uploadSignphoto.url = `${proxy.$settings.axiosRequestConfig.baseURL}/appsys/user/user/sign/upload/${userId.value}`;
        getSignphoto();
        formData.value = {
          name: res.data.name,
          nameEn: res.data.nameEn,
          sex: res.data.sex,
          mobile: res.data.mobile,
          homeTel: res.data.homeTel,
          email: res.data.email,
          officeTel: res.data.officeTel,
          fax: res.data.fax,
          homeAddress: res.data.homeAddress
        };
        initFormData.value = { ...formData.value };
        setTimeout(() => {
          isChangeForm.value = true;
          // oldFormData.value=form.getFieldsValue();
        });
      }
    })
    .catch((err) => {
      console.error(err);
    });
}

function getSignphoto() {
  return getTokenAvatar(`${proxy.$settings.axiosRequestConfig.baseURL}/appsys/user/user/sign/get/${userId.value}`, 'signphotoImageUrl');
}

function handleSignphotoChange(info) {
  if (info.file.status === 'uploading') {
    signphotoLoading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    getBase64(info.file.originFileObj, (imageUrl) => {
      signphotoImageUrl.value = imageUrl;
      signphotoLoading.value = false;
    });
    if (info.file.response?.responseBody === false) {
      proxy.$message.error(info.file.response?.errorDesc || '上传出错！');
    } else if (info.file.response?.responseBody === true) {
      proxy.$message.success(info.file.response?.message || '上传成功！');
    }
  }
}
function beforeUploadSignphoto(file) {
  const isImageFile =
    file.type === 'image/jpeg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/png' ||
    file.type === 'image/bmp' ||
    file.type === 'image/gif';
  if (!isImageFile) {
    proxy.$message.error('请选择图片类文件！');
  }
  const checkFileSize = file.size / 1024 < 512;
  if (!checkFileSize) {
    proxy.$message.error('请选择小于512KB的签名图片！');
  }
  return isImageFile && checkFileSize;
}
function deleteSignphotoImage() {
  proxy.$confirm({
    title: '确认要删除电子签名吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      signphotoImageUrl.value = '';
      deleteSignphoto(userId.value).then((res) => {
        if (res.success) {
          proxy.$message.success(res.message || '删除成功!');
        }
      });
    }
  });
}

// 获取用户头像
function getTokenAvatar(url: string, variableName: string) {
  const xmlhttp = new XMLHttpRequest();
  xmlhttp.open('GET', url, true);
  xmlhttp.responseType = 'arraybuffer';
  xmlhttp.setRequestHeader('X-Access-Token', token);
  // 请求头中增加租户信息
  if (getCookie(TENANT_ID)) {
    xmlhttp.setRequestHeader('X-Tenant-Id', getCookie(TENANT_ID));
  }

  // if (this.$getMicroToken()) {
  //   xmlhttp.setRequestHeader(
  //     'x-kong-api-key',
  //     'bearer ' + this.$getMicroToken()
  //   );
  // }
  xmlhttp.onload = () => {
    if (xmlhttp.status === 200) {
      if (xmlhttp.response.byteLength) {
        const buffer = new Uint8Array(xmlhttp.response).reduce((data, byte) => data + String.fromCharCode(byte), '');
        if (variableName === 'imageUrl') {
          imageUrl.value = `data:image/png;base64,${btoa(buffer)}`;
        } else if (variableName === 'signphotoImageUrl') {
          signphotoImageUrl.value = `data:image/png;base64,${btoa(buffer)}`;
        }
      }
    }
  };
  xmlhttp.send();
}

// 上传前验证
function beforeUpload(file) {
  const isImageFile =
    file.type === 'image/jpeg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/png' ||
    file.type === 'image/bmp' ||
    file.type === 'image/gif';
  if (!isImageFile) {
    proxy.$message.error('请选择图片类文件！');
  }
  const checkFileSize = file.size / 1024 < 512;
  if (!checkFileSize) {
    proxy.$message.error('请选择小于512KB的头像图片！');
  }
  return isImageFile && checkFileSize;
}
// 上传
function handleChange(info) {
  if (info.file.status === 'uploading') {
    // loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    getBase64(info.file.originFileObj, (url) => {
      if (info.file.response.retCode === '200') {
        imageUrl.value = url;
        // loading.value = false;
      } else {
        proxy.$message.error(info.file.response.errorDesc || info.file.response.message);
      }
    });
  }
}
function handleDelete() {
  proxy.$confirm({
    title: '确认要删除头像吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      imageUrl.value = '';
      deleteLogo().then((res) => {
        if (res.success) {
          proxy.$message.success(res.message || '删除成功!');
        }
      });
    }
  });
}
// 重置表单
function resetForm() {
  formData.value = { ...initFormData.value } as formDataType;
  setTimeout(() => {
    isDataChange.value = false;
  });
  formRef.value.resetFields();
}
// 保存
function handleSave() {
  formRef.value.validate().then(() => {
    updateUserInfo(formData.value).then((res: any) => {
      if (res.success) {
        proxy.$message.success('保存成功！');
        isDataChange.value = false;
      }
    });
  });
}
</script>

<style lang="less" scoped>
.personal-info {
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
  .basic-title {
    // display: block;
    padding: 20px;
    font-size: 16px;
  }
  .user-avatar {
    width: 100px;
    height: 100px;
    margin: -1px 0 0 -1px;
    padding: 5px;
    border-radius: 8px;
  }
  .defaultAvatar {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 60px;
    background: #b8d4ff;
  }
  .img-action {
    display: flex;
    .alert-text {
      margin-top: 15px;
      margin-left: 8px;
      width: 255px;
      height: 32px;
      line-height: 16px;
      .ant-alert-icon {
        position: absolute;
        top: 9.5px;
        left: 15px;
      }
    }
  }
  .avatar-uploader {
    :deep(.ant-upload) {
      display: inline-block;
      width: 100px;
      height: 100px;
      border-radius: 8px;
      background: #fafafa;
      text-align: center;
      cursor: pointer;
    }

    :deep(.anticon-plus),
    :deep(.anticon-loading) {
      margin-top: 20px;
      font-size: 22px;
    }

    .ant-upload-text {
      margin-top: 8px;
    }
  }
}
</style>
